import './styles'

import {
    Canvas as FabricCanvas,
    Point  as FabricPoint,
    Line   as FabricLine,
    util   as fabricUtil,
} from 'fabric'

import {
    debounce,
} from 'lodash'





import { testId } from './typescripts/tools'





function 主程序 () {
    const fabricCanvas1 = new FabricCanvas('canvas1')

    const line1 = new FabricLine(
        [ 50, 50, 210, 210 ],

        {
            stroke: 'red',
            strokeWidth: 5,
        }
    )

    line1.on('moving',   event => line1CalcGlobalCoords())
    line1.on('rotating', event => line1CalcGlobalCoords())
    line1.on('scaling',  event => line1CalcGlobalCoords())
    // line1.on('resizing', event => line1CalcGlobalCoords())

    fabricCanvas1.add(line1)
    fabricCanvas1.setActiveObject(line1)

    fabricCanvas1.on('mouse:move', debounce(event => {
        // if (fabricCanvas1.getActiveObject()) { return }

        if (!event.e || !event.e.target) { return }

        const eventRaw = event.e as MouseEvent

        console.log(eventRaw.offsetX, eventRaw.offsetY)
    }, 100))


    const line1CalcGlobalCoords = debounce(function () {
        const { x1, x2, y1, y2, width, height } = line1

        const w_half = width  / 2
        const h_half = height / 2

        const line1Matrix = line1.calcTransformMatrix()

        const points_Local_ToGeometryCenter = [
            new FabricPoint((x1 < x2 ? -1 : 1) * w_half, (y1 < y2 ? -1 : 1) * h_half),
            new FabricPoint((x2 < x1 ? -1 : 1) * w_half, (y2 < y1 ? -1 : 1) * h_half),
        ]

        const points_Global = points_Local_ToGeometryCenter.map(point => {
            return point.transform(fabricUtil.multiplyTransformMatrices(
                fabricCanvas1.viewportTransform || [ 1, 0, 0, 1, 0, 0 ],
                line1Matrix
            ))
        })

        console.log(
            // '宽', +width .toFixed(1),
            // '      ',
            // '高', +height.toFixed(1),
            '\n局', ...points_Local_ToGeometryCenter.map(p => [ +p.x.toFixed(1), +p.y.toFixed(1) ]),
            '\n全', ...points_Global.map(p => [ +p.x.toFixed(1), +p.y.toFixed(1) ]),

            // line1.getBoundingRect(),
            // '\n', line1.getCoords(),
            '\n----',
        )
    }, 200)
}

主程序()
